Skip to main content

Middle of the Linked List

LeetCode 908 | Difficulty: Easy​

Easy

Problem Description​

Given the head of a singly linked list, return the middle node of the linked list.

If there are two middle nodes, return the second middle node.

Example 1:

Input: head = [1,2,3,4,5]
Output: [3,4,5]
Explanation: The middle node of the list is node 3.

Example 2:

Input: head = [1,2,3,4,5,6]
Output: [4,5,6]
Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.

Constraints:

- The number of nodes in the list is in the range `[1, 100]`.

- `1 <= Node.val <= 100`

Topics: Linked List, Two Pointers


Approach​

Linked List​

Use pointer manipulation. Common techniques: dummy head node to simplify edge cases, fast/slow pointers for cycle detection and middle finding, prev/curr/next pattern for reversal.

When to use

In-place list manipulation, cycle detection, merging lists, finding the k-th node.


Solutions​

Solution 1: C# (Best: 80 ms)​

MetricValue
Runtime80 ms
Memory38.3 MB
Date2022-02-02
Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode MiddleNode(ListNode head) {
ListNode slow = head, fast = head;
while(fast.next != null)
{
slow = slow.next;
fast = fast.next;
if(fast.next != null) fast = fast.next;
}
return slow;
}
}
πŸ“œ 1 more C# submission(s)

Submission (2022-02-02) β€” 123 ms, 37 MB​

/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int val=0, ListNode next=null) {
* this.val = val;
* this.next = next;
* }
* }
*/
public class Solution {
public ListNode MiddleNode(ListNode head) {
ListNode slow = head, fast = head;
while(fast != null && fast.next != null)
{
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}

Complexity Analysis​

ApproachTimeSpace
Two Pointers$O(n)$$O(1)$
Linked List$O(n)$$O(1)$

Interview Tips​

Key Points
  • Start by clarifying edge cases: empty input, single element, all duplicates.
  • Draw the pointer changes before coding. A dummy head node simplifies edge cases.